package com.warehouse.service.impl;

import com.warehouse.entity.Product;
import com.warehouse.entity.StockIn;
import com.warehouse.mapper.StockInMapper;
import com.warehouse.service.ProductService;
import com.warehouse.service.StockInService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class StockInServiceImpl implements StockInService {

    @Autowired
    private StockInMapper stockInMapper;

    @Autowired
    private ProductService productService;

    @Override
    public List<StockIn> getAllStockIns() {
        return stockInMapper.selectAll();
    }

    @Override
    public StockIn getStockInById(Long id) {
        return stockInMapper.selectById(id);
    }

    @Override
    public List<StockIn> getStockInsByProductId(Long productId) {
        return stockInMapper.selectByProductId(productId);
    }

    @Override
    public List<StockIn> getStockInsByDateRange(LocalDateTime startTime, LocalDateTime endTime) {
        return stockInMapper.selectByDateRange(startTime, endTime);
    }

    @Override
    public List<StockIn> getStockInsBySupplier(String supplier) {
        return stockInMapper.selectBySupplier(supplier);
    }

    @Override
    @Transactional
    public StockIn createStockIn(StockIn stockIn) {
        stockInMapper.insert(stockIn);
        
        // 更新商品库存
        Product product = productService.getProductById(stockIn.getProductId());
        if (product != null) {
            int newQuantity = product.getStockQuantity() + stockIn.getQuantity();
            productService.updateStock(stockIn.getProductId(), newQuantity);
        }
        
        return stockIn;
    }

    @Override
    @Transactional
    public boolean importFromExcel(MultipartFile file) {
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            List<StockIn> stockIns = new ArrayList<>();

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                StockIn stockIn = new StockIn();
                
                // 读取Excel行数据
                String productName = getCellValueAsString(row.getCell(0));
                String specification = getCellValueAsString(row.getCell(1));
                Integer quantity = getCellValueAsInteger(row.getCell(2));
                BigDecimal unitPrice = getCellValueAsBigDecimal(row.getCell(3));
                String supplier = getCellValueAsString(row.getCell(4));
                String batchNumber = getCellValueAsString(row.getCell(5));
                String operator = getCellValueAsString(row.getCell(6));
                String remark = getCellValueAsString(row.getCell(7));

                // 根据商品名称查找商品ID
                List<Product> products = productService.getProductsByName(productName);
                if (!products.isEmpty()) {
                    Product product = products.get(0);
                    stockIn.setProductId(product.getId());
                    stockIn.setQuantity(quantity != null ? quantity : 0);
                    stockIn.setUnitPrice(unitPrice);
                    stockIn.setTotalAmount(unitPrice != null && quantity != null ? 
                        unitPrice.multiply(new BigDecimal(quantity)) : BigDecimal.ZERO);
                    stockIn.setSupplier(supplier);
                    stockIn.setBatchNumber(batchNumber);
                    stockIn.setOperator(operator);
                    stockIn.setRemark(remark);
                    stockIn.setStockInTime(LocalDateTime.now());

                    stockIns.add(stockIn);
                }
            }

            // 批量保存入库记录
            if (!stockIns.isEmpty()) {
                stockInMapper.insertBatch(stockIns);
                
                // 更新商品库存
                for (StockIn stockIn : stockIns) {
                    Product product = productService.getProductById(stockIn.getProductId());
                    if (product != null) {
                        int newQuantity = product.getStockQuantity() + stockIn.getQuantity();
                        productService.updateStock(stockIn.getProductId(), newQuantity);
                    }
                }
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateStockIn(StockIn stockIn) {
        return stockInMapper.update(stockIn) > 0;
    }

    @Override
    @Transactional
    public boolean deleteStockIn(Long id) {
        return stockInMapper.deleteById(id) > 0;
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            default:
                return null;
        }
    }

    private Integer getCellValueAsInteger(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case NUMERIC:
                return (int) cell.getNumericCellValue();
            case STRING:
                try {
                    return Integer.parseInt(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return null;
                }
            default:
                return null;
        }
    }

    private BigDecimal getCellValueAsBigDecimal(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case NUMERIC:
                return BigDecimal.valueOf(cell.getNumericCellValue());
            case STRING:
                try {
                    return new BigDecimal(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return null;
                }
            default:
                return null;
        }
    }
    
    @Override
    public long getTodayStockInCount() {
        return stockInMapper.countToday();
    }
} 